import * as API from '../../api/orderApi';
import * as util from '../../utils/util';
import * as config from '../../config'
let app = getApp ();

Page({
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.audioCtx = wx.createAudioContext('myAudio')
    // this.audioPlay()
  },
  /**
   * 页面的初始数据
   */
  data: {
    poster: 'http://y.gtimg.cn/music/photo_new/T002R300x300M000003rsKF44GyaSk.jpg?max_age=2592000',
    name: '此时此刻',
    author: '许巍',
    src: '../../templates/111.mp3',

    hasRequest: false,
    clickConfirmBtn: false,
    showMarker: 0,
    isFilterType: false,
    total: 0,
    currentTab: 0,
    tabs: ['全部', '待支付', '已支付',  '已完成'],
    operates: [{
      isChecked: false,
      iconPath: 'order/query.png',
      clsName: 'query'
    },
    {
      isChecked: false,
      iconPath: 'order/sort.png',
      clsName: 'sort'
    }
    ],
    sortArr: [{
      text: '默认排序',
      orderByWhat: '',
      sort: '0'
    },
    {
      text: '下单时间降序',
      orderByWhat: 0,
      sort: '1'
    }, {
      text: '下单时间升序',
      orderByWhat: 0,
      sort: '0'
    }],
    showOrderFinishedDialog: false,
    showOrderCancelDialog: false,
    curOrderId: '',
    curitemIdx: 0,
    dataSource: [],
    pageNumber: 1,
    pageSize: 6,
    orderByWhat: '', //默认排序
    sort: '0',
    customName: '',
    startTime: '',
    endTime: '',
    goodsDeliveryDateBegin: '',
    goodsDeliveryDateEnd: '',
    customeSelectName: '',
    customSelectIndex: -1,
    sortSelectIndex: 0,
    sortHeight: '680rpx',
    showChooseItems: 0, // 1-->选择状态 2-->选择时间或交期
    date: new Date().getTime(),
    clickWhichDate: '',
    customArr: []
  },
  
  navbarTap(e) {
    const index = e.target.dataset.idx;
    this.setData({
      currentTab: index
    });
    this.outOfFilter(true);
  },
  deliveryDateChanged: function (e) {
    let type = this.data.clickWhichDate;
    this.setData({
      [type]: e.detail.value.timeStamp
    })
    setTimeout(() => {
      this.setData({
        showChooseItems: 0
      })
    }, 600)
  },
  onOrderOperate: function (e) {
    const index = e.target.dataset.value;
    this.setData({
      showMarker: index + 1
    });

  },
  handleshowChooseItems: function (e) {
    //idx   3-->时间弹框 4-->采购公司弹框
    let idx = e.currentTarget.dataset.flag;
    switch (idx) {
      case '3':
        this.handleDatepick(e)
        break;
      case '4':
        this.getCustom()
        break;
    }
    this.setData({
      showChooseItems: idx
    })
  },
  customItemSelect: function (e) {
    let idx = e.detail.index;
    this.setData({
      customSelectIndex: idx,
      customName: e.detail.list.name,
      showChooseItems: 0
    })
  },
  clearCustom: function () {
    this.setData({
      customSelectIndex: -1,
      showChooseItems: 0,
      customName: ''
    })
  },
  isOnDefaultCondition: function () {
    const isEmpty = !this.data.startTime && !this.data.endTime && !this.data.goodsDeliveryDateBegin && !this.data.goodsDeliveryDateEnd && !this.data.customName;
    return isEmpty;
  },
  queryFormSubmit() {
    if (this.isOnDefaultCondition())
      return this.setData({
        showMarker: 0,
        isFilterType: false
      });
    this.setData({
      showMarker: 0,
      dataSource: [],
      isFilterType: true,
      clickConfirmBtn: true //有效查詢
    })
    this.getOrderList();
  },
  queryFormReset() {
    this.resetQueryChange();
  },
  handleCancelBtnClick: function () {
    this.setData({
      showChooseItems: 0
    })
  },
  handleDatepick: function (e) {
    let type = e.target.dataset.type,
      date = e.target.dataset.date;
    if (type) {
      this.setData({
        [type]: date,
        clickWhichDate: type,
        date: date || new Date().getTime()
      })
    }
  },
  getCustom: function () {
    let that = this;
    let token = wx.getStorageSync('token');
    API.getCustom({
      token: token
    }).then(res => {
      that.setData({
        customArr: res.customList
      })
    }, err => {
      if (err == 999) {
        // util.toast(err);
        // wx.switchTab({
        //   url: '../../home/home'
        // });
      } else {
        util.toast(err);
      }
    });
  },
  resetQueryChange(isTabChange) { //tab 切换重置
    let postBody = {
      pageNumber: 1,
      pageSize: this.data.pageSize,
      // startTime: '',
      // endTime: '',
      goodsDeliveryDateBegin: '',
      goodsDeliveryDateEnd: '',
      customName: ''
    }
    this.setData({
      startTime: '',
      endTime:''
    })
    if(!this.data.currentTab){
    } else if(this.data.currentTab==3){
      postBody.status=4
    } else{
      postBody.status=this.data.currentTab-1
    }
    if ((this.data.clickConfirmBtn && !this.isOnDefaultCondition()) || isTabChange) {
      this.getOrderList(postBody)
      postBody.hasRequest = false;
      postBody.clickConfirmBtn = false;
      postBody.dataSource = [],
        postBody.customeSelectName = '全部',
        postBody.customSelectIndex = -1
    }
    this.setData(postBody);
  },
  outOfFilter: function (isTabChange) {
    this.resetQueryChange(isTabChange);
    this.setData({
      isFilterType: false
    })
  },
  hideMarker: function () {
    this.setData({
      showMarker: 0,
      showChooseItems: 0
    })
  },
  jumpToSearch() {
    util.preventMoreClick(this, () => {
      wx.navigateTo({
        url: './searchOrder/searchOrder'
      })
    })
  },
  sortItemSelect: function (e) {
    let idx = e.detail.index;
    console.log(e.detail, 9999)
    this.setData({
      sortSelectIndex: idx,
      sort: e.detail.list.sort,
      orderByWhat: e.detail.list.orderByWhat,
      showChooseItems: 0,
      showMarker: 0,
      dataSource: []
    });
    this.getOrderList({
      sort: e.detail.list.sort,
      orderByWhat: e.detail.list.orderByWhat,
      pageNumber: 1,
      pageSize: this.data.pageSize
    })
  },
  getOrderList(obj) {
    const that = this;
    let postBody = {
      pageNumber: this.data.pageNumber || 1,
      pageSize: this.data.pageSize || 6,
      deliverStatus: this.data.currentTab == 0 ? '' : this.data.currentTab - 1,
      orderByWhat: this.data.orderByWhat,
      // startTime: util.formatQueryTime(this.data.startTime) || '',
      // endTime: util.formatQueryTime(this.data.endTime) || '',
      goodsDeliveryDateBegin: util.formatQueryTime(this.data.goodsDeliveryDateBegin) || '',
      goodsDeliveryDateEnd: util.formatQueryTime(this.data.goodsDeliveryDateEnd) || '',
      sort: this.data.sort,
      customName: this.data.customName
    };
    if(this.data.startTime){
      postBody.startTime=util.formatQueryTime(this.data.startTime)
    }
    if(this.data.endTime){
      postBody.endTime=util.formatQueryTime(this.data.endTime)
    }
    wx.showLoading({
      title: '正在加载数据'
    })
    if (obj)
      postBody = Object.assign({}, postBody, obj)
    that.setData({
      hasRequest: false
    })
    API.getOrderList(postBody).then(res => {
      const dataList = that.data.dataSource.concat(res.data.records);
      that.setData({
        dataSource: dataList,
        total: res.data.total,
        hasRequest: true
      });
      wx.stopPullDownRefresh();
      wx.hideLoading();
    }, err => {
      wx.showToast({
        icon: 'none',
        title: err || '读取失败'
      });
    })
  },
  cancelOrder: function (e) {
    let that = this;
    const idx = e.detail.index;
    const id = e.detail.id;
    const key = "dataSource[" + idx + "].deliverStatus";
    this.setData({
      showOrderCancelDialog: true,
      curOrderId: id,
      curitemIdx: idx
    })

  },
  finishOrder: function (e) {
    const idx = e.detail.index;
    const id = e.detail.id;
    this.setData({
      showOrderFinishedDialog: true,
      curOrderId: id,
      curitemIdx: idx
    })

  },
  finishOrderFormSubmit: function (e) { //完成订单弹框
    let that = this;
    // if (e.detail.type == 'submit') {
      const key = "dataSource[" + this.data.curitemIdx + "].deliverStatus";
      API.finishOrder(this.data.curOrderId, {status: 4}).then(res => {
        // console.log(res, '----------')
        that.resetQueryChange(true);
        // if (that.data.currentTab == 1) { //未完成tab
        //   const data = that.data.dataSource.splice(that.data.curitemIdx, 1)
        //   this.setData({
        //     dataSource: that.data.dataSource,
        //     total: --this.data.total
        //   });
        //   that.toast('订单已完成');
        // } else { //全部tab
        //   that.setData({
        //     [key]: 1
        //   })
        // }
      }, err => {
        console.log(err, '===========')
      })
    // }
    this.setData({
      showOrderFinishedDialog: false
    })
  },
  cancelOrderFormSubmit: function (e) { //取消订单弹框
    let that = this;
    if (e.detail.type == 'submit') {
      const key = "dataSource[" + this.data.curitemIdx + "].deliverStatus";
      API.cancelOrder({
        id: this.data.curOrderId,
        cancelReason: e.detail.value
      }).then(res => {
        if (that.data.currentTab == 1) { //未完成tab
          that.data.dataSource.splice(that.data.curitemIdx, 1);
          this.setData({
            dataSource: that.data.dataSource,
            total: --this.data.total
          })
          that.toast('订单已取消');
        } else { //全部tab
          that.setData({
            [key]: 2
          })
        }
      }, err => {

      })
    }
    this.setData({
      showOrderCancelDialog: false
    })

  },
  toast: function (title) {
    wx.showToast({
      icon: 'none',
      title: title,
      duration: 2000
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.getOrderList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.audioCtx = wx.createAudioContext('myAudio')
    // setTimeout(()=>{
      // this.ydyyd()
    //   this.audioPlay()
    // },1200)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let token = wx.getStorageSync('token');
    this.setData({
      dataSource: [],
      total: 0,
      hasRequest: false
    });
    this.getOrderList();
    token&&this.test()
  },
  audioPlay: function () {
    this.audioCtx.play()
  },
  test(){
    var _this = this;
    let sid=app.globalData.userInfo.id
  // var {receiveMemberId, sendMemberId} = this.data
  //建立连接
  wx.connectSocket({
    url: config.wsUrl+sid,//本地
    success: function () {
      console.log('websocket连接成功~')
    },
    fail: function () {
      console.log('websocket连接失败~')
    },
  })

  //连接成功
  wx.onSocketOpen(function () {
    console.log('onSocketOpen','连接成功,真正的成功');
  })
  
//  接收服务器的消息事件
 wx.onSocketMessage(function(res){
  console.log(res)
  _this.audioPlay()
   _this.resetQueryChange(true)
 },
)

  //  监听连接关闭
  wx.onSocketClose(function(){
    console.log('监听 WebSocket 连接关闭事件')
  })
  },
  ydyyd(){
    wx.sendSocketMessage({
      data: 'dfsdfsdfsdfsdfsdfsdfsd',
      success: (res) =>{
        console.log(res)
      },
      fail: (err)=>{
          console.log('sendSocketMessage','失败')
      }
     })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      pageNumber: 1,
      dataSource: []
    });
    let postBody={}
    if(!this.data.currentTab){
    } else if(this.data.currentTab==3){
      postBody.status=4
    } else{
      postBody.status=this.data.currentTab-1
    }
    this.getOrderList(postBody);
  },
  donothing: function () {
    return false;
  },
  hideDoubleMarker: function () {
    this.setData({
      showChooseItems: 0
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let postBody={}
    if(!this.data.currentTab){
    } else if(this.data.currentTab==3){
      postBody.status=4
    } else{
      postBody.status=this.data.currentTab-1
    }
    var hasAtLeastOnePage = this.data.dataSource.length >= this.data.pageSize;
    if (!hasAtLeastOnePage) return;
    var hasMore = this.data.dataSource.length < this.data.total;
    if (hasMore) {
      this.setData({
        pageNumber: ++this.data.pageNumber
      });
      this.getOrderList(postBody);
    }
  },

})